<!DOCTYPE html>












  


<html class="theme-next mist use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">









  
  
  <link rel="stylesheet" media="all" href="/lib/Han/dist/han.min.css?v=3.3">




<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />



















  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.lug.ustc.edu.cn/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.4.2" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.jpg?v=6.4.2">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.jpg?v=6.4.2">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.jpg?v=6.4.2">


  <link rel="mask-icon" href="/images/logo.svg?v=6.4.2" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '6.4.2',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  




  <meta name="description" content="@RequestParam@RequestParam用于将请求参数区数据映射到功能处理方法的参数上。 1public String queryUserName(@RequestParam String userName) @RequestParam注解主要有哪些参数： value：参数名字，即入参的请求参数名字，如username表示请求的参数区中的名字为username的参数的值将传入； req">
<meta name="keywords" content="spring">
<meta property="og:type" content="article">
<meta property="og:title" content="springMvc之注解参数">
<meta property="og:url" content="https://devzhao.com/post/585c5232.html">
<meta property="og:site_name" content="学而时习之">
<meta property="og:description" content="@RequestParam@RequestParam用于将请求参数区数据映射到功能处理方法的参数上。 1public String queryUserName(@RequestParam String userName) @RequestParam注解主要有哪些参数： value：参数名字，即入参的请求参数名字，如username表示请求的参数区中的名字为username的参数的值将传入； req">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2018-10-13T13:33:09.940Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="springMvc之注解参数">
<meta name="twitter:description" content="@RequestParam@RequestParam用于将请求参数区数据映射到功能处理方法的参数上。 1public String queryUserName(@RequestParam String userName) @RequestParam注解主要有哪些参数： value：参数名字，即入参的请求参数名字，如username表示请求的参数区中的名字为username的参数的值将传入； req">






  <link rel="canonical" href="https://devzhao.com/post/585c5232.html"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>springMvc之注解参数 | 学而时习之</title>
  






  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?b8fcd96e6d9e134b3c9551097ed074a4";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  <div id="showImgFullScrn" style="display: none;"><img id="showImgFullScrnImg" src="" style="max-height:100%"></div>

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">学而时习之</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <h1 class="site-subtitle" itemprop="description">时间就是力量</h1>
      
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-shortcut">
    <a href="/shortcut/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-shirtsinbulk"></i> <br />快捷</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-about">
    <a href="/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  
    

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://devzhao.com/post/585c5232.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zhaohan">
      <meta itemprop="description" content="教，是最好的学">
      <meta itemprop="image" content="http://qnfile.devzhao.com/blog/2018-10-12-125720.jpg#/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="学而时习之">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">springMvc之注解参数
              
            
          </h2>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2017-02-22 17:47:11" itemprop="dateCreated datePublished" datetime="2017-02-22T17:47:11+08:00">2017-02-22</time>
            

            
          </span>

          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/post/585c5232.html#comments" itemprop="discussionUrl">
                  <span class="post-meta-item-text">评论数：</span> <span class="post-comments-count valine-comment-count" data-xid="/post/585c5232.html" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
             <span id="/post/585c5232.html" class="leancloud_visitors" data-flag-title="springMvc之注解参数">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数：</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          
            <div class="post-symbolscount">
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">本文字数：</span>
                
                <span title="本文字数">11k</span>
              

              

              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body han-init-context" itemprop="articleBody">

      
      

      
        <h1 id="RequestParam"><a href="#RequestParam" class="headerlink" title="@RequestParam"></a>@RequestParam</h1><p>@RequestParam用于将请求参数区数据映射到功能处理方法的参数上。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">public String queryUserName(@RequestParam String userName)</span><br></pre></td></tr></table></figure>
<h2 id="RequestParam注解主要有哪些参数："><a href="#RequestParam注解主要有哪些参数：" class="headerlink" title="@RequestParam注解主要有哪些参数："></a>@RequestParam注解主要有哪些参数：</h2><ul>
<li>value：参数名字，即入参的请求参数名字，如username表示请求的参数区中的名字为username的参数的值将传入；</li>
<li>required：是否必须，默认是true，表示请求中一定要有相应的参数，否则将报404错误码；</li>
<li>defaultValue：默认值，表示如果请求中没有同名参数时的默认值，默认值可以是SpEL表达式，如“#{systemProperties[‘java.vm.version’]}”。</li>
</ul>
<p>表示请求中可以没有名字为username的参数，如果没有默认为null，此处需要注意如下几点：</p>
<ul>
<li>原子类型：必须有值，否则抛出异常，如果允许空值请使用包装类代替。</li>
<li>Boolean包装类型类型：默认Boolean.FALSE，其他引用类型默认为null。</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">public String queryUserName(@RequestParam(value=&quot;userName&quot; ,required =false ) String userName)</span><br><span class="line"></span><br><span class="line">public String requestparam5(  </span><br><span class="line">@RequestParam(value=&quot;username&quot;, required=true, defaultValue=&quot;zhang&quot;) String username)</span><br></pre></td></tr></table></figure>
<h2 id="同一个字段多个值"><a href="#同一个字段多个值" class="headerlink" title="同一个字段多个值"></a>同一个字段多个值</h2><ol>
<li><p>在传递参数的时候如果是url?userName=zhangsan&amp;userName=wangwu时怎么办呢?</p>
</li>
<li><p>其实在实际list参数入参的数据为“zhangsan,wangwu”，即多个数据之间使用“，”分割，即url?list=zhangsan,wangwu  </p>
</li>
</ol>
<p>我们应该使用如下方式来接收多个请求参数：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">public String requestparam8(@RequestParam(value=&quot;userName&quot;) String []  userNames)    </span><br><span class="line"></span><br><span class="line">public String requestparam8(@RequestParam(value=&quot;list&quot;) List&lt;String&gt; list)</span><br></pre></td></tr></table></figure>
<hr>
<h1 id="PathVariable"><a href="#PathVariable" class="headerlink" title="@PathVariable"></a>@PathVariable</h1><p>通过@PathVariable可以绑定占位符参数到方法参数中。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">@RequestMapping(value=&quot;/users/&#123;userId&#125;/topics/&#123;topicId&#125;&quot;)  </span><br><span class="line">public String test(   @PathVariable(value=&quot;userId&quot;) int userId,    @PathVariable(value=&quot;topicId&quot;) int topicId)</span><br></pre></td></tr></table></figure>
<p>如请求的URL为“控制器URL/users/123/topics/456”，则自动将URL中模板变量{userId}和{topicId}绑定到通过@PathVariable注解的同名参数上，即入参后userId=123、topicId=456。</p>
<h1 id="CookieValue"><a href="#CookieValue" class="headerlink" title="@CookieValue"></a>@CookieValue</h1><p>@CookieValue用于将请求的Cookie数据映射到功能处理方法的参数上。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">public String test(@CookieValue(value=&quot;JSESSIONID&quot;, defaultValue=&quot;&quot;) String sessionId)</span><br></pre></td></tr></table></figure>
<p>这里的defaultValue表示Cookie中没有JSESSIONID时默认为空。</p>
<h1 id="RequestHeader"><a href="#RequestHeader" class="headerlink" title="@RequestHeader"></a>@RequestHeader</h1><p>@RequestHeader用于将请求的头信息区数据映射到功能处理方法的参数上。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">@RequestMapping(value=&quot;/header&quot;)  </span><br><span class="line">public String test(  </span><br><span class="line">       @RequestHeader(&quot;User-Agent&quot;) String userAgent,  </span><br><span class="line">       @RequestHeader(value=&quot;Accept&quot;) String[] accepts)</span><br></pre></td></tr></table></figure>
<p>如上配置将自动将请求头“User-Agent”值入参到userAgent参数上，并将“Accept”请求头值入参到accepts参数上。</p>
<h1 id="ModelAttribute"><a href="#ModelAttribute" class="headerlink" title="@ModelAttribute"></a>@ModelAttribute</h1><p>@ModelAttribute绑定请求参数到命令对象</p>
<p>@ModelAttribute一个具有如下三个作用：</p>
<ul>
<li>①绑定请求参数到命令对象：放在功能处理方法的入参上时，用于将多个请求参数绑定到一个命令对象，从而简化绑定流程，而且自动暴露为模型数据用于视图页面展示时使用；</li>
<li>②暴露表单引用对象为模型数据：放在处理器的一般方法（非功能处理方法）上时，是为表单准备要展示的表单引用对象，如注册时需要选择的所在城市等，而且在执行功能处理方法（@RequestMapping注解的方法）之前，自动添加到模型对象中，用于视图页面展示时使用；</li>
<li>③暴露@RequestMapping方法返回值为模型数据：放在功能处理方法的返回值上时，是暴露功能处理方法的返回值为模型数据，用于视图页面展示时使用。</li>
</ul>
<h2 id="一、绑定请求参数到命令对象"><a href="#一、绑定请求参数到命令对象" class="headerlink" title="一、绑定请求参数到命令对象"></a>一、绑定请求参数到命令对象</h2><p>如用户登录，我们需要捕获用户登录的请求参数（用户名、密码）并封装为用户对象，此时我们可以使用@ModelAttribute绑定多个请求参数到我们的命令对象。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">public String test1(@ModelAttribute(&quot;user&quot;) UserModel user)</span><br></pre></td></tr></table></figure>
<p><em>绑定请求参数到命令对象支持对象图导航式的绑定，如请求参数包含“?username=zhang&amp;password=123&amp;workInfo.city=bj”自动绑定到user中的workInfo属性的city属性中。</em></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">@RequestMapping(value=&quot;/model2/&#123;username&#125;&quot;)  </span><br><span class="line">public String test2(@ModelAttribute(&quot;model&quot;) DataBinderTestModel model)</span><br></pre></td></tr></table></figure>
<p><em>URI模板变量也能自动绑定到命令对象中，当你请求的URL中包含“bool=yes&amp;schooInfo.specialty=computer&amp;hobbyList[0]=program&amp;hobbyList[1]=music&amp;map[key1]=value1&amp;map[key2]=value2&amp;state=blocked”会自动绑定到命令对象上。</em></p>
<p><strong>当URI模板变量和请求参数同名时，URI模板变量具有高优先权。</strong></p>
<h2 id="二、暴露表单引用对象为模型数据"><a href="#二、暴露表单引用对象为模型数据" class="headerlink" title="二、暴露表单引用对象为模型数据"></a>二、暴露表单引用对象为模型数据</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">@ModelAttribute(&quot;cityList&quot;)  </span><br><span class="line">public List&lt;String&gt; cityList() &#123;  </span><br><span class="line">    return Arrays.asList(&quot;北京&quot;, &quot;山东&quot;);  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>如上代码会在执行功能处理方法之前执行，并将其自动添加到模型对象中，在功能处理方法中调用Model 入参的containsAttribute(“cityList”)将会返回true。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">@ModelAttribute(&quot;user&quot;)  //①  </span><br><span class="line">public UserModel getUser(@RequestParam(value=&quot;username&quot;, defaultValue=&quot;&quot;) String username) &#123;  </span><br><span class="line">//TODO 去数据库根据用户名查找用户对象  </span><br><span class="line">UserModel user = new UserModel();  </span><br><span class="line">user.setRealname(&quot;zhang&quot;);  </span><br><span class="line">     return user;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>如你要修改用户资料时一般需要根据用户的编号/用户名查找用户来进行编辑，此时可以通过如上代码查找要编辑的用户。</p>
<p>也可以进行一些默认值的处理。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">@RequestMapping(value=&quot;/model1&quot;) //②  </span><br><span class="line">public String test1(@ModelAttribute(&quot;user&quot;) UserModel user, Model model)</span><br></pre></td></tr></table></figure>
<p>此处我们看到①和②有同名的命令对象，那Spring Web MVC内部如何处理的呢：</p>
<p>(1、首先执行@ModelAttribute注解的方法，准备视图展示时所需要的模型数据；@ModelAttribute注解方法形式参数规则和@RequestMapping规则一样，如可以有@RequestParam等；</p>
<p>（2、执行@RequestMapping注解方法，进行模型绑定时首先查找模型数据中是否含有同名对象，如果有直接使用，如果没有通过反射创建一个，因此②处的user将使用①处返回的命令对象。即②处的user等于①处的user。</p>
<h2 id="三、暴露-RequestMapping方法返回值为模型数据"><a href="#三、暴露-RequestMapping方法返回值为模型数据" class="headerlink" title="三、暴露@RequestMapping方法返回值为模型数据"></a>三、暴露@RequestMapping方法返回值为模型数据</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">public @ModelAttribute(&quot;user2&quot;) UserModel test3(@ModelAttribute(&quot;user2&quot;) UserModel user)</span><br></pre></td></tr></table></figure>
<p><em>返回值类型是命令对象类型，而且通过@ModelAttribute(“user2”)注解，此时会暴露返回值到模型数据（名字为user2）中供视图展示使用。那哪个视图应该展示呢？此时Spring Web MVC会根据RequestToViewNameTranslator进行逻辑视图名的翻译</em></p>
<p>此时又有问题了，@RequestMapping注解方法的入参user暴露到模型数据中的名字也是user2，其实我们能猜到：<br><em>@ModelAttribute注解的返回值会覆盖@RequestMapping注解方法中的@ModelAttribute注解的同名命令对象。</em></p>
<h2 id="四、匿名绑定命令参数"><a href="#四、匿名绑定命令参数" class="headerlink" title="四、匿名绑定命令参数"></a>四、匿名绑定命令参数</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">public String test4(@ModelAttribute UserModel user, Model model)  </span><br><span class="line"></span><br><span class="line">public String test5(UserModel user, Model model)</span><br></pre></td></tr></table></figure>
<p>上面两种用法没有为命令对象提供暴露到模型数据中的名字，此时的名字是什么呢？Spring Web MVC自动将简单类名（首字母小写）作为名字暴露。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">public @ModelAttribute List&lt;String&gt; test6()  </span><br><span class="line">public @ModelAttribute List&lt;UserModel&gt; test7()</span><br></pre></td></tr></table></figure>
<p>对于集合类型（Collection接口的实现者们，包括数组），生成的模型对象属性名为“简单类名（首字母小写）”+“List”，如List<string>生成的模型对象属性名为“stringList”，List<usermodel>生成的模型对象属性名为“userModelList”。</usermodel></string></p>
<p>其他情况一律都是使用简单类名（首字母小写）作为模型对象属性名，如Map&lt;String, UserModel&gt;类型的模型对象属性名为“map”。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">/** </span><br><span class="line"> * 传递的参数的名字必须要与实体类的属性set方法后面的字符串匹配的上才能接收到参数，首字符的大小写不区分 </span><br><span class="line"> * 请求中传的参数只要是能和参数列表里面的变量名或者实体里面的set后面的字符串匹配的上就能接收到 a </span><br><span class="line"> *  </span><br><span class="line"> */  </span><br><span class="line">@RequestMapping(&quot;/toPerson1.do&quot;)  </span><br><span class="line">public String toPerson1(String name, Integer age, String address,  </span><br><span class="line">             Date birthday) &#123;  </span><br><span class="line">           System.out.println(name + &quot; &quot; + age + &quot; &quot; + address + &quot; &quot; + birthday);  </span><br><span class="line">           return &quot;jsp1/index&quot;;  </span><br><span class="line">&#125;  </span><br><span class="line">  </span><br><span class="line">/** </span><br><span class="line"> * 注册时间类型的属性编辑器，将String转化为Date </span><br><span class="line"> */  </span><br><span class="line">@InitBinder  </span><br><span class="line">public void initBinder(ServletRequestDataBinder binder) &#123;  </span><br><span class="line">    binder.registerCustomEditor(Date.class, new CustomDateEditor(  </span><br><span class="line">            new SimpleDateFormat(&quot;yyyy-MM-dd&quot;), true));  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="SessionAttributes"><a href="#SessionAttributes" class="headerlink" title="SessionAttributes"></a>SessionAttributes</h1><p>有时候我们需要在多次请求之间保持数据，一般情况需要我们明确的调用HttpSession的API来存取会话数据，如多步骤提交的表单。Spring Web MVC提供了@SessionAttributes进行请求间透明的存取会话数据。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">//1、在控制器类头上添加@SessionAttributes注解  </span><br><span class="line">@SessionAttributes(value = &#123;&quot;user&quot;&#125;)    //①  </span><br><span class="line">public class SessionAttributeController   </span><br><span class="line">  </span><br><span class="line">//2、@ModelAttribute注解的方法进行表单引用对象的创建  </span><br><span class="line">@ModelAttribute(&quot;user&quot;)    //②  </span><br><span class="line">public UserModel initUser()   </span><br><span class="line">  </span><br><span class="line">//3、@RequestMapping注解方法的@ModelAttribute注解的参数进行命令对象的绑定  </span><br><span class="line">@RequestMapping(&quot;/session1&quot;)   //③  </span><br><span class="line">public String session1(@ModelAttribute(&quot;user&quot;) UserModel user)  </span><br><span class="line">  </span><br><span class="line">//4、通过SessionStatus的setComplete()方法清除@SessionAttributes指定的会话数据  </span><br><span class="line">@RequestMapping(&quot;/session2&quot;)   //③  </span><br><span class="line">public String session(@ModelAttribute(&quot;user&quot;) UserModel user, SessionStatus status) &#123;  </span><br><span class="line">    if(true) &#123; //④  </span><br><span class="line">        status.setComplete();  </span><br><span class="line">    &#125;  </span><br><span class="line">    return &quot;success&quot;;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>@SessionAttributes(value = {“user”})含义：</p>
<p>@SessionAttributes(value = {“user”}) 标识将模型数据中的名字为“user” 的对象存储到会话中（默认HttpSession），此处value指定将模型数据中的哪些数据（名字进行匹配）存储到会话中，此外还有一个types属性表示模型数据中的哪些类型的对象存储到会话范围内，如果同时指定value和types属性则那些名字和类型都匹配的对象才能存储到会话范围内。</p>
<p>包含@SessionAttributes的执行流程如下所示：</p>
<ul>
<li>① 首先根据@SessionAttributes注解信息查找会话内的对象放入到模型数据中；</li>
<li>② 执行@ModelAttribute注解的方法：如果模型数据中包含同名的数据，则不执行@ModelAttribute注解方法进行准备表单引用数据，而是使用①步骤中的会话数据；如果模型数据中不包含同名的数据，执行@ModelAttribute注解的方法并将返回值添加到模型数据中；</li>
<li>③ 执行@RequestMapping方法，绑定@ModelAttribute注解的参数：查找模型数据中是否有@ModelAttribute注解的同名对象，如果有直接使用，否则通过反射创建一个；并将请求参数绑定到该命令对象；</li>
</ul>
<p>此处需要注意：如果使用@SessionAttributes注解控制器类之后，③步骤一定是从模型对象中取得同名的命令对象，如果模型数据中不存在将抛出HttpSessionRequiredException Expected session attribute ‘user’(Spring3.1)</p>
<p>或HttpSessionRequiredException Session attribute ‘user’ required - not found in session(Spring3.0)异常。</p>
<p>④ 如果会话可以销毁了，如多步骤提交表单的最后一步，此时可以调用SessionStatus对象的setComplete()标识当前会话的@SessionAttributes指定的数据可以清理了，此时当@RequestMapping功能处理方法执行完毕会进行清理会话数据。</p>
<p>我们通过Spring Web MVC的源代码验证一下吧，此处我们分析的是Spring3.1的RequestMappingHandlerAdapter，读者可以自行验证Spring3.0的AnnotationMethodHandlerAdapter，流程一样：</p>
<p>1、RequestMappingHandlerAdapter.invokeHandlerMethod</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">//1、RequestMappingHandlerAdapter首先调用ModelFactory的initModel方法准备模型数据：  </span><br><span class="line">modelFactory.initModel(webRequest, mavContainer, requestMappingMethod);  </span><br><span class="line">//2、调用@RequestMapping注解的功能处理方法  </span><br><span class="line">requestMappingMethod.invokeAndHandle(webRequest, mavContainer);  </span><br><span class="line">//3、更新/合并模型数据  </span><br><span class="line">modelFactory.updateModel(webRequest, mavContainer);</span><br></pre></td></tr></table></figure>
<p>2、ModelFactory.initModel</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">Map&lt;String, ?&gt; attributesInSession = this.sessionAttributesHandler.retrieveAttributes(request);  </span><br><span class="line">//1.1、将与@SessionAttributes注解相关的会话对象放入模型数据中  </span><br><span class="line">mavContainer.mergeAttributes(attributesInSession);  </span><br><span class="line">//1.2、调用@ModelAttribute方法添加表单引用对象  </span><br><span class="line">invokeModelAttributeMethods(request, mavContainer);  </span><br><span class="line">//1.3、验证模型数据中是否包含@SessionAttributes注解相关的会话对象，不包含抛出异常  </span><br><span class="line">for (String name : findSessionAttributeArguments(handlerMethod)) &#123;  </span><br><span class="line">    if (!mavContainer.containsAttribute(name)) &#123;  </span><br><span class="line">        //1.4、此处防止在@ModelAttribute注解方法又添加了会话对象  </span><br><span class="line">        //如在@ModelAttribute注解方法调用session.setAttribute(&quot;user&quot;, new UserModel());  </span><br><span class="line">        Object value = this.sessionAttributesHandler.retrieveAttribute(request, name);  </span><br><span class="line">        if (value == null) &#123;  </span><br><span class="line">            throw new HttpSessionRequiredException(&quot;Expected session attribute &apos;&quot; + name + &quot;&apos;&quot;);  </span><br><span class="line">        &#125;  </span><br><span class="line">        mavContainer.addAttribute(name, value);  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>3、ModelFactory.invokeModelAttributeMethods</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">for (InvocableHandlerMethod attrMethod : this.attributeMethods) &#123;  </span><br><span class="line">    String modelName = attrMethod.getMethodAnnotation(ModelAttribute.class).value();   </span><br><span class="line">    //1.2.1、如果模型数据中包含同名数据则不再添加  </span><br><span class="line">    if (mavContainer.containsAttribute(modelName)) &#123;  </span><br><span class="line">        continue;  </span><br><span class="line">    &#125;  </span><br><span class="line">    //1.2.2、调用@ModelAttribute注解方法并将返回值添加到模型数据中，此处省略实现代码  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>4、requestMappingMethod.invokeAndHandle 调用功能处理方法，此处省略</p>
<p>5、ModelFactory.updateMode 更新模型数据</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">//3.1、如果会话被标识为完成，此时从会话中清除@SessionAttributes注解相关的会话对象  </span><br><span class="line">if (mavContainer.getSessionStatus().isComplete())&#123;   </span><br><span class="line">    this.sessionAttributesHandler.cleanupAttributes(request);  </span><br><span class="line">&#125;  </span><br><span class="line">//3.2、如果会话没有完成，将模型数据中的@SessionAttributes注解相关的对象添加到会话中  </span><br><span class="line">else &#123;  </span><br><span class="line">    this.sessionAttributesHandler.storeAttributes(request, mavContainer.getModel());  </span><br><span class="line">&#125;  </span><br><span class="line">//省略部分代码</span><br></pre></td></tr></table></figure>
<h1 id="Value"><a href="#Value" class="headerlink" title="@Value"></a>@Value</h1><p>@Value用于将一个SpEL表达式结果映射到到功能处理方法的参数上。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">public String test(@Value(&quot;#&#123;systemProperties[&apos;java.vm.version&apos;]&#125;&quot;) String jvmVersion)</span><br></pre></td></tr></table></figure>
<h1 id="RequestBody"><a href="#RequestBody" class="headerlink" title="@RequestBody"></a>@RequestBody</h1><p>这个注释它指示一个方法的参数绑定到一个web请求的body。它支持Servlet环境中的注释处理器方法。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">@Controller</span><br><span class="line"></span><br><span class="line">public class HelloWorldController &#123;</span><br><span class="line"></span><br><span class="line">    @RequestMapping(&quot;/hello.do&quot;)   </span><br><span class="line"></span><br><span class="line">   public String helloWorld(Model model,@RequestBody String reqBody) &#123;</span><br><span class="line"></span><br><span class="line">       model.addAttribute(&quot;message&quot;, reqBody);</span><br><span class="line"></span><br><span class="line">      return &quot;helloWorld&quot;;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这时这个参数reqBody的值是请求页面的form表单的所有值。</p>
<h1 id="ResponseBody"><a href="#ResponseBody" class="headerlink" title="@ResponseBody"></a>@ResponseBody</h1><p>这个注释它指示一个方法的返回值应该绑定到一个web响应的body中。它支持Servlet环境中的注释处理器方法。</p>
<p>应用@ResponseBody将会跳过视图处理，而是调用合适HttpMessageConverter，将返回值写入输出流。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">@Controller</span><br><span class="line"></span><br><span class="line">@RequestMapping(&quot;/a&quot;)</span><br><span class="line"></span><br><span class="line">public class HelloWorldController &#123;</span><br><span class="line"></span><br><span class="line">    @RequestMapping(&quot;/b&quot;)</span><br><span class="line"></span><br><span class="line">    @ResponseBody</span><br><span class="line"></span><br><span class="line">   public String helloWorld() &#123;</span><br><span class="line"></span><br><span class="line">      return &quot;helloWorld&quot;;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>或者这样定义</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">@Controller</span><br><span class="line"></span><br><span class="line">public class HelloWorldController &#123;</span><br><span class="line"></span><br><span class="line">    @RequestMapping(&quot;/a/b&quot;)</span><br><span class="line"></span><br><span class="line">   public @ResponseBody String helloWorld() &#123;</span><br><span class="line"></span><br><span class="line">      return &quot;helloWorld&quot;;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这时访问/a/b时，不是返回一个view名为helloWorld的视图，而是作出一个响应，其内容为helloWorld。</p>
<hr>
<p>参考：</p>
<p><a href="http://www.cnblogs.com/wangchuanfu/p/5913310.html" target="_blank" rel="noopener">http://www.cnblogs.com/wangchuanfu/p/5913310.html</a></p>
<p><a href="http://www.cnblogs.com/wenlj/p/4645292.html" target="_blank" rel="noopener">http://www.cnblogs.com/wenlj/p/4645292.html</a></p>

      
    </div>

    

    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持分享输出，感谢你的支持！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.jpg" alt="zhaohan 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="zhaohan 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>zhaohan</li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://devzhao.com/post/585c5232.html" title="springMvc之注解参数">https://devzhao.com/post/585c5232.html</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明出处！</li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/spring/" rel="tag"># spring</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/post/ce66c137.html" rel="next" title="spring下使用swagger接口服务">
                <i class="fa fa-chevron-left"></i> spring下使用swagger接口服务
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/post/c686304c.html" rel="prev" title="“扁平化管理”与“奥卡姆剃刀定律”">
                “扁平化管理”与“奥卡姆剃刀定律” <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="http://qnfile.devzhao.com/blog/2018-10-12-125720.jpg#/images/avatar.gif"
                alt="zhaohan" />
            
              <p class="site-author-name" itemprop="name">zhaohan</p>
              <p class="site-description motion-element" itemprop="description">教，是最好的学</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">148</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">33</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">29</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#RequestParam"><span class="nav-number">1.</span> <span class="nav-text">@RequestParam</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#RequestParam注解主要有哪些参数："><span class="nav-number">1.1.</span> <span class="nav-text">@RequestParam注解主要有哪些参数：</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#同一个字段多个值"><span class="nav-number">1.2.</span> <span class="nav-text">同一个字段多个值</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#PathVariable"><span class="nav-number">2.</span> <span class="nav-text">@PathVariable</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#CookieValue"><span class="nav-number">3.</span> <span class="nav-text">@CookieValue</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#RequestHeader"><span class="nav-number">4.</span> <span class="nav-text">@RequestHeader</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#ModelAttribute"><span class="nav-number">5.</span> <span class="nav-text">@ModelAttribute</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#一、绑定请求参数到命令对象"><span class="nav-number">5.1.</span> <span class="nav-text">一、绑定请求参数到命令对象</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#二、暴露表单引用对象为模型数据"><span class="nav-number">5.2.</span> <span class="nav-text">二、暴露表单引用对象为模型数据</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#三、暴露-RequestMapping方法返回值为模型数据"><span class="nav-number">5.3.</span> <span class="nav-text">三、暴露@RequestMapping方法返回值为模型数据</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#四、匿名绑定命令参数"><span class="nav-number">5.4.</span> <span class="nav-text">四、匿名绑定命令参数</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#SessionAttributes"><span class="nav-number">6.</span> <span class="nav-text">SessionAttributes</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Value"><span class="nav-number">7.</span> <span class="nav-text">@Value</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#RequestBody"><span class="nav-number">8.</span> <span class="nav-text">@RequestBody</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#ResponseBody"><span class="nav-number">9.</span> <span class="nav-text">@ResponseBody</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">zhaohan</span>

  

  
</div>


  










        
<div class="busuanzi-count">
  <!--<script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>-->

  <script async src="//cdn.busuanzi.ibruce.info/cdn/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv" title="总访客量">
      <!-- <i class="fa fa-user-circle"></i> -->
      <i>已有</i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      <i>位访客浏览过此网站</i>
    </span>
  

  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    
	
    

    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.4.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.4.2"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.4.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.4.2"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.4.2"></script>



  



  








  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  
  
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick';
    guest = guest.split(',').filter(function (item) {
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: true,
        notify: false,
        appId: 'z99UqRJEaGqxYLDPSPSx5jih-gzGzoHsz',
        appKey: 'N7MTJbRdufk8MAg3yeK6Gs9U',
        placeholder: '说点什么吧...',
        avatar:'mm',
        meta:guest,
        pageSize:'10' || 10,
        visitor: false
    });
  </script>



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script>
    
    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();

      Counter('get', '/classes/Counter', { where: JSON.stringify({ url }) })
        .done(function ({ results }) {
          if (results.length > 0) {
            var counter = results[0];
            
            Counter('put', `/classes/Counter/${counter.objectId}`, JSON.stringify({ time: { "__op":"Increment", "amount":1 } }))
            
            .done(function () {
                  var $element = $(document.getElementById(url));
                  $element.find('.leancloud-visitors-count').text(counter.time + 1);
            })
            
            .fail(function ({ responseJSON }) {
                console.log('Failed to save Visitor num, with error message: ' + responseJSON.error);
            })
          } else {
            
              Counter('post', '/classes/Counter', JSON.stringify({ title: title, url: url, time: 1}))
                .done(function () {
                  var $element = $(document.getElementById(url));
                  $element.find('.leancloud-visitors-count').text(1);
                })
                .fail(function () {
                  console.log('Failed to create');
                });
            
          }
        })
      .fail(function ({ responseJSON }) {
        console.log('LeanCloud Counter Error:' + responseJSON.code + " " + responseJSON.error);
      });
    }
    

    $(function() {
      $.get('https://app-router.leancloud.cn/2/route?appId=' + "z99UqRJEaGqxYLDPSPSx5jih-gzGzoHsz")
        .done(function ({ api_server }) {
          var Counter = function (method, url, data) {
            return $.ajax({
              method: method,
              url: `https://${api_server}/1.1${url}`,
              headers: {
                'X-LC-Id': "z99UqRJEaGqxYLDPSPSx5jih-gzGzoHsz",
                'X-LC-Key': "N7MTJbRdufk8MAg3yeK6Gs9U",
                'Content-Type': 'application/json',
              },
              data: data,
            });
          };
          
          addCount(Counter);
          
        })
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  

  
  

  

  

  

  

  

</body>
</html>
